<template>
  <div class="app-container">
    <el-button type="primary" v-if="$unit.isPower('create directive')" @click="handleAddRole">添加人员</el-button>
    <!-- <router-link :to="'/branchoffice/index'">
      <el-button type="default" style="margin-left: 10px">分公司管理</el-button>
    </router-link> -->
    <el-table
      stripe
      :data="userList"
      style="width: 100%; margin-top: 10px"
      border
    >
      <el-table-column align="center" width="80px" label="姓名编号">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" width="150px" label="姓名">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="用户名" width="230px">
        <template slot-scope="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色">
        <template slot-scope="scope">
          <!-- <el-button type="primary" round v-for=" (item,index) in scope.row.role" :key = index size = "mini">
            {{item}}
          </el-button> -->
          <div
            v-for="(item, index) in scope.row.has_manyrole"
            :key="index"
            style="
              text-align: center;
              padding: 3px;
              border-radius: 7px;
              font-size: 10px;
              color: #fff;
              margin: 1px;
              background: cornflowerblue;
              float: left;
            "
          >
            {{ item.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" width="200" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.$index, scope.row)"
             v-if="$unit.isPower('update directive')"
          >编辑</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.$index, scope.row)"
             v-if="$unit.isPower('delete directive')"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        ref="pager"
        background
        :current-page.sync="pageIndex"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === '添加人员' ? '添加人员' : '编辑人员'"
    >
      <el-form :model="userInfo" label-width="80px" label-position="left">
        <el-form-item label="姓名 *">
          <el-input v-model="userInfo.name" placeholder="请输入姓名" />
        </el-form-item>
        <!-- //当dialog是添加管理员时显示 -->
        <el-form-item v-show="dialogType === '添加人员'" label="用户名 *">
          <el-input v-model="userInfo.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码 *">
          <el-input
            v-model="userInfo.password"
            :show-password="true"
            placeholder="请输入密码,最少六位"
          />
        </el-form-item>

        <el-form-item v-show="dialogType != '添加人员'" label="确认密码 *">
          <el-input
            v-model="userInfo.confirmPassword"
            :show-password="true"
            placeholder="请输入密码,最少六位"
          />
        </el-form-item>
        {{userInfo.has_manyrole}}
        <el-form-item label="角色 *">
          <el-select
            v-model="userInfo.role"
            placeholder="请选择"
            value-key="id"
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SwitchRoles from './components/SwitchRoles'
import {
  getAllUser,
  getAllUserPage,
  deleteUser,
  insertUser,
  updateUser,
  getRoles
} from '@/api/user'
import { getClassify } from '@/api/classify'
import { getInfo } from '@/api/user'

export default {
  name: 'PagePermission',
  components: { SwitchRoles },
  data() {
    return {
      pageIndex: 0, // 第几页
      pageSize: 2, // 一页数量
      total: 0, // 总页数
      currentPage: 0, // 当前页
      last_page: 0, // 最后一夜
      is_admin: false, // 是否是管理员
      dialogVisible: false, // dialog显示隐藏
      dialogType: '', // dialog的标题
      roles: '', // 角色
      perId: '', // 编辑单个id 变量
      userList: [], // 用户信息
      userInfo: {
        name: '',
        username: '',
        password: '',
        roles: [],
        confirmPassword: ''
      },
      roleOptions: ''
    }
  },
  created() {
    this.getUserInfo()
    this.selectAllUser()
  },

  methods: {
    handleSelectChange() {
      this.$forceUpdate()
    },
    // 下一页
    sizeChangeHandle: function(size) {
      this.pagesize = size
    },
    currentChangeHandle: function(val) {
      this.currentIndex = val
      return new Promise((resolve, reject) => {
        getAllUserPage(val).then((response) => {
          // 调用分页方法 下一页 查询
          this.userList = response.data.data
        })
      })
    },
    selectAllUser() {
      // console.log(this.$route.path);
      new Promise((reselve, reject) => {
        getAllUser().then((response) => {
          // 获取数据显示
          // 将后台拿到的数据转换
          this.userList = response.data.data
          this.total = response.data.total
          this.pageSize = response.data.to
          this.currentPage = response.data.current_page
          this.last_page = response.data.last_page
        })
      })
    },

    selectPage() {
      // console.log(this.$route.path);
      new Promise((reselve, reject) => {
        getAllUser().then((response) => {
          // 获取数据显示
          // 将后台拿到的数据转换
          this.total = response.data.total
          this.pageSize = response.data.to
          this.last_page = response.data.last_page
        })
      })
    },

    // 添加角色按钮
    handleAddRole() {
      this.dialogType = '添加人员'
      this.dialogVisible = true
      this.userInfo.username = ''
      this.userInfo.password = ''
      this.userInfo.confirmPassword = ''
      // 打开dialog框后查询角色内容 填充到select框中
      new Promise((resolve, reject) => {
        getRoles().then((response) => {
          // 填充数据
          this.roleOptions = response.data
          console.log(this.roleOptions)

        })
      })
    },

    // 提交dialog框
    confirmRole() {
      if (this.dialogType == '添加人员') {
        // console.log(this.userInfo);
        // 添加角色 请求
        new Promise((resolve, rejetc) => {
          insertUser({
            userInfo: this.userInfo
          }).then((response) => {
            this.$message({
              type: 'success',
              message: '人员添加成功!'
            })
            // 添加权限成功后清除表单输入框内容
            this.userInfo.name = ''
            this.userInfo.email = ''
            this.userInfo.role = ''
            this.userInfo.password = ''
            this.userInfo.confirmPassword = ''
            // 关闭dialog框
            this.dialogVisible = false
            this.selectPage()
            const page =
              this.total % 8 == 0 ? this.last_page + 1 : this.last_page
            this.currentChangeHandle(page)
            this.pageIndex = page
          })
        })
      } else {
        // console.log(this.perList);
        // console.log(this.userInfo);
        // console.log(this.perId);
        // 编辑权限信息 请求
        new Promise((resolve, reject) => {
          updateUser({
            id: this.perId,
            userInfo: this.userInfo
          }).then((response) => {
            this.$message({
              type: 'success',
              message: '修改人员信息成功'
            })
            // 角色修改成功后清除表单输入框内容
            this.userInfo.name = ''
            this.userInfo.username = ''
            this.userInfo.password = ''
            this.userInfo.role = ''
            this.userInfo.confirmPassword = ''
            // 关闭dialog框
            this.dialogVisible = false
            this.currentChangeHandle(this.currentIndex)
            this.pageIndex = this.currentIndex
          })
        })
      }
    },
    // 取消dialog框
    cancelRole() {
      // 关闭dialog框
      this.dialogVisible = false
      // 取消弹框后 清除 表单内容
      this.userInfo.name = ''
      this.userInfo.username = ''
      this.userInfo.password = ''
      this.userInfo.role = ''
      this.userInfo.confirmPassword = ''
      this.perId = ''
    },
    // 管理员编辑
    handleEdit($index, row) {
      this.dialogType = '编辑管理员'
      this.dialogVisible = true
      // 将当前行的id 赋值给perId 后续修改传值id
      this.perId = row.id
      this.userInfo.name = row.name
      this.userInfo.role = row.role[0]
      this.userInfo.username = row.username

      new Promise((resolve, reject) => {
        getRoles().then((response) => {
          // 填充数据
          this.roleOptions = response.data
        })
      })
    },
    // 权限删除
    handleDelete($index, row) {
      this.$confirm('确认删除?', '警告', {
        configButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warring'
      }).then(() => {
        new Promise((resolve, reject) => {
          deleteUser({ id: row.id }).then((response) => {
            this.selectPage()
            const page =
              this.total % 8 == 1 ? this.last_page - 1 : this.last_page
            this.currentChangeHandle(page)
            this.pageIndex = page
          })
        })
      })
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then((response) => {
          // this.username = response.data.name; //当前登录用户的姓名
          if (response.data.role[0] == 'administrators') {
            this.is_admin = true
          } else {
            this.is_admin = false
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .label_per ul {
    width: 520px;
    height: auto;
    list-style: none;
    padding: 0px;
  }
  // .label_per ul li {
  //   width: 120px;
  //   height: 40px;
  //   float: left;
  // }
}
</style>
